package com.example.bootdemo.service.impl;

import com.example.bootdemo.pojo.Role;
import com.example.bootdemo.pojo.User;
import com.example.bootdemo.pojo.UserRole;
import com.example.bootdemo.repository.RoleRepository;
import com.example.bootdemo.repository.TblUserRepository;
import com.example.bootdemo.repository.UserRoleRepository;
import com.example.bootdemo.service.UserSecurityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserSecurityServiceImpl implements UserSecurityService {

    @Autowired
    private TblUserRepository userRepository;

    @Autowired
    private RoleRepository roleRepository;

    @Autowired
    private UserRoleRepository userRoleRepository;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    @Transactional
    public User saveUser(User user) {
        String passwordText = user.getPassword();
        //用户数据入库前需要对密码进行编码处理，也是一种加密方式
        user.setPassword(passwordEncoder.encode(passwordText));

        return userRepository.save(user);
    }

    @Override
    @Transactional
    public void deleteByUsername(String username) {
        userRepository.deleteUserByUsername(username);
    }

    @Override
    @Transactional
    public Role saveRole(Role role) {

        return roleRepository.save(role);
    }

    @Override
    @Transactional
    public void deleteRoleByRoleId(String roleId) {
        roleRepository.deleteById(roleId);
    }

    @Override
    @Transactional
    public UserRole saveUserRole(UserRole userRole) {
        return userRoleRepository.save(userRole);
    }

    @Override
    @Transactional
    public void deleteUserRoleByUnionId(Long userId, String roleId) {

        userRoleRepository.deleteUserRoleByUnionId(userId,roleId);
    }
}
